package com.ilxqx.framework.security.service;

import com.ilxqx.framework.security.po.UserDetailsImpl;
import com.ilxqx.framework.system.entity.SysUser;
import com.ilxqx.framework.system.enumeration.SysUserStatusEnum;
import com.ilxqx.framework.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 用户认证服务类
 * @author venus
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserService sysUserService;

    @Autowired
    public UserDetailsServiceImpl(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("账号为[{}]的用户登录系统，系统开始验证其是否存在...", username);
        Optional<SysUser> sysUserOptional = sysUserService.getByAccount(username);

        if (sysUserOptional.isEmpty()) {
            // 账号不存在
            log.warn("账号[{}]不存在，登录失败", username);
            throw new UsernameNotFoundException("账号不存在");
        }

        log.info("账号[{}]存在，之后将交由SpringSecurity框架验证其合法性了", username);
        SysUser sysUser = sysUserOptional.get();

        // 账号存在，构建用户验证对象并返回
        return new UserDetailsImpl(sysUser.getUserId(), sysUser.getName(), sysUser.getAccount(), sysUser.getPassword(), SysUserStatusEnum.ENABLED.equals(sysUser.getStatus()));
    }

}
